package com.test.qpbgboot.show.service.impl;

import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.utils.BaseUtils;
import com.test.qpbgboot.evaluation.mapper.EscortEvaluationMapper;
import com.test.qpbgboot.schedule.mapper.OrderMapper;
import com.test.qpbgboot.show.mapper.EscortMapper;
import com.test.qpbgboot.show.mapper.ShopMapper;
import com.test.qpbgboot.show.pojo.dto.EscortQuery;
import com.test.qpbgboot.show.pojo.dto.EscortSaveParam;
import com.test.qpbgboot.show.pojo.dto.ShopQuery;
import com.test.qpbgboot.show.pojo.entity.Escort;
import com.test.qpbgboot.show.pojo.vo.EscortVO;
import com.test.qpbgboot.show.pojo.vo.ShopVO;
import com.test.qpbgboot.show.service.EscortService;
import com.test.qpbgboot.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class EscortServiceImpl implements EscortService {

    @Value("${aliyun.oss.bucket-url}")
    private String bucketUrl;
    @Autowired
    private EscortMapper escortMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EscortEvaluationMapper escortEvaluationMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<EscortVO> escortSelect(EscortQuery escortQuery) {
        log.debug("陪玩查询业务，参数:L{}", escortQuery);
        List<EscortVO> escortVOList = escortMapper
                .selectEscortVObyEscortQuery(escortQuery);
        if (escortVOList != null && !escortVOList.isEmpty()) {
            for (EscortVO escortVO : escortVOList) {
                additionalField(escortVO);
            }
        }
        log.debug("陪玩查询结果:{}", escortVOList);
        return escortVOList;
    }

    @Override
    public void escortSave(EscortSaveParam escortSaveParam) {
        log.debug("陪玩保存，参数:{}", escortSaveParam);
        Escort escort = new Escort();
        BeanUtils.copyProperties(escortSaveParam, escort);

        List<String> status = Arrays.asList("1", "0");
        if (!status.contains(escort.getVisible())) {
            throw new ServiceException(ResultStatus.ILLEGAL_ARGUMENT, "是否展示设置错误");
        }

        if (escort.getVisible().equals("1") && escort.getPrice() == null) {
            throw new ServiceException(ResultStatus.ILLEGAL_ARGUMENT, "展示的陪玩价格不能为空");
        }

        if (userMapper.selectUserVObyId(escort.getUserId()) == null) {
            throw new ServiceException(ResultStatus.INVALID_ID, "用户id无效");
        }

        Long id = escortMapper.selectIdByUserId(escort.getUserId());
        if (id != null && !id.equals(escort.getId())
                || id == null && escort.getId() != null) {
            throw new ServiceException(ResultStatus.ILLEGAL_ARGUMENT, "用户id与陪玩id不匹配");
        }

        if (escort.getShopId() != null) {
            ShopQuery shopQuery = new ShopQuery();
            shopQuery.setId(escort.getShopId());
            List<ShopVO> shopVOList = shopMapper.selectShopVObyShopsQuery(shopQuery);
            if (shopVOList == null || shopVOList.isEmpty()) {
                throw new ServiceException(ResultStatus.INVALID_ID, "店家id无效");
            }
        }

        List<String> imgUrlList = escortSaveParam.getImgUrlList();
        String imgsUrl = BaseUtils.imgListToString(imgUrlList);
        imgsUrl = imgsUrl.replaceAll(bucketUrl, "bucketUrl");
        escort.setImgsUrl(imgsUrl);

        if (escort.getId() == null) {
            escortMapper.insert(escort);
        } else {
            escortMapper.update(escort);
        }

    }

    @Override
    public void escortDelete(Long escortId) {
        log.debug("陪玩删除业务，参数:{}", escortId);
        escortMapper.deleteById(escortId);
    }

    private void additionalField(EscortVO escortVO) {
        if (escortVO.getShopId() != null) {
            escortVO.setShopName(shopMapper
                    .selectShopNameById(escortVO.getShopId()));
        }
        String tagIds = escortVO.getTagIds();
        if (tagIds != null) {
            List<String> tagIdStringList = Arrays.asList(tagIds.split(","));
            List<Long> tagIdList = tagIdStringList.stream().filter(Objects::nonNull)
                    .map(Long::parseLong).collect(Collectors.toList());
            escortVO.setTagIdList(tagIdList);
        }
        String imgsUrl = escortVO.getImgsUrl();
        imgsUrl = imgsUrl.replaceAll("bucketUrl", bucketUrl);
        List<String> imgUrlList = BaseUtils.imgStringToList(imgsUrl);
        escortVO.setImgUrlList(imgUrlList);

        Double avgRating = escortEvaluationMapper
                .selectAvgRatingByEscortId(escortVO.getId());
        escortVO.setAvgRating(avgRating != null ? avgRating : (double) 0);

        escortVO.setOrderNum(orderMapper
                .selectOrderNumInMonthByEscortId(escortVO.getId()));

        Long likes = escortEvaluationMapper
                .selectLikesByEscortId(escortVO.getId());
        escortVO.setLikes(likes != null ? likes : 0);
    }
}
